import { app, shell, BrowserWindow, ipcMain, BrowserView } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1920,
    height: 670,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  // 更新BrowserView的位置和大小
  function updateViewsSize(mainWindow, view1, view2, view3, position = 3 / 6) {
    const { width, height } = mainWindow.getBounds()
    const leftWidth = width * position
    const rightWidth = (width - leftWidth) * 0.5

    view1.setBounds({ x: 0, y: 0, width: leftWidth, height: height })
    view2.setBounds({ x: leftWidth, y: 0, width: rightWidth, height: height })
    view3.setBounds({ x: leftWidth + rightWidth, y: 0, width: rightWidth, height: height })
  }

  // 创建两个BrowserView
  const view1 = new BrowserView()
  const view2 = new BrowserView()
  const view3 = new BrowserView()

  // 设置BrowserView的大小和位置
  const { width, height } = mainWindow.getBounds()
  const splitRatio = 3.35 / 6 //
  const leftWidth = width * splitRatio
  const rightWidth = (width - leftWidth) * 0.5

  view1.setBounds({ x: 0, y: 0, width: leftWidth, height: height })
  view2.setBounds({
    x: leftWidth,
    y: 0,
    width: rightWidth,
    height: height,
    backgroundColor: '#ffffff', // 设置背景色
    transparent: true
  })
  view3.setBounds({ x: leftWidth + rightWidth, y: 0, width: rightWidth, height: height })

  // 将BrowserView添加到主窗口
  mainWindow.addBrowserView(view1)
  mainWindow.addBrowserView(view2)
  mainWindow.addBrowserView(view3)

  // 监听窗口大小变化事件
  mainWindow.on('resize', () => {
    updateViewsSize(mainWindow, view1, view2, view3, splitRatio)
  })
  // 设置初始缩放比例
  view1.webContents.setZoomFactor(0.2) // 默认缩放比例
  view2.webContents.setZoomFactor(0.3) // 默认缩放比例
  view2.webContents.setZoomFactor(0.3) // 默认缩放比例

  // 加载URL
  view1.webContents.loadURL('https://www.ttyingqiu.com/jczq')
  view2.webContents.loadURL('https://m.leisu.com/live/saicheng')
  view3.webContents.loadURL('http://117.78.2.23:7788/tt/index.html#/')

  // 监听view1页面加载完成事件
  view1.webContents.on('did-finish-load', () => {
    // const className = 'goFixedNew'; // 替换为您要移除的类名
    // const script = `
    //   const elements = document.getElementsByClassName('${className}');
    //   while (elements.length > 0) {
    //     elements[0].parentNode.removeChild(elements[0]);
    //   }
    // `;
    const classNames = ['goFixedNew', 'mainTab', 'positionBar', 'footer mt30', 'linkTd'] // 替换为您要移除的类名数组
    const script = `
      const classNames = ${JSON.stringify(classNames)};
      classNames.forEach(className => {
        const elements = document.getElementsByClassName(className);
        while (elements.length > 0) {
          elements[0].parentNode.removeChild(elements[0]);
        }
      });
    `
    view1.webContents.executeJavaScript(script)
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  // 注册IPC通道，用于接收分割线位置的变化
  ipcMain.on('resize-divider', (event, position) => {
    updateViewsSize(mainWindow, view1, view2, view3, position)
  })

  // 注册IPC通道，用于移除view1中的节点
  ipcMain.on('remove-node-by-class', (event, classNames) => {
    const script = `
      const classNames = ${JSON.stringify(classNames)};
      classNames.forEach(className => {
        const elements = document.getElementsByClassName(className);
        while (elements.length > 0) {
          elements[0].parentNode.removeChild(elements[0]);
        }
      });
    `
    view1.webContents.executeJavaScript(script)
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
